<template >
  <div id="detail">
    <!-- 导航条 -->
    <DetailNavBar
      class="detail-bav"
      @titleClick="titleClick"
      ref="nav"
    ></DetailNavBar>
    <!-- 滚动 -->
    <Scroll
      class="wrapper"
      ref="scroll"
      :probe-type="3"
      @scroll="wrapperScroll"
    >
      <!-- <ul>
        <li v-for="(item, index) in $store.state.cartList" :key="index">{{item}}</li>
      </ul> -->
      <!-- 详情页轮播图 -->
      <DetailSwiper :top-images="topImages"></DetailSwiper>
      <!-- 商品基本信息 -->
      <DetailBaseInfo :goods="goods"></DetailBaseInfo>
      <!-- 店铺信息 -->
      <DetailShopInfo :shop="shop"></DetailShopInfo>
      <!-- 图片展示 -->
      <DetailGoodsInfo
        :detail-info="detailInfo"
        @imageLoad="imageLoad"
      ></DetailGoodsInfo>
      <DetailParamInfo ref="params" :param-info="paramInfo"></DetailParamInfo>
      <DetailCommentInfo
        ref="comment"
        :comment-info="commentInfo"
      ></DetailCommentInfo>
      <GoodsList ref="recommend" :goods="recommends"></GoodsList>
    </Scroll>
    <BackTop @click="backClick" v-show="isShowBackTop"></BackTop>
    <DetailBottomBar @addToCart="addToCart"></DetailBottomBar>
    <!-- 弹窗 -->
    <Toast :message="message" :isShow="isShow"></Toast>
  </div>
</template>

<script>
import DetailNavBar from "./childComps/DetailNavBar";
import DetailSwiper from "./childComps/DetailSwiper";
import DetailBaseInfo from "./childComps/DetailBaseInfo";
import DetailShopInfo from "./childComps/DetailShopInfo";
import DetailGoodsInfo from "./childComps/DetailGoodsInfo";
import DetailParamInfo from "./childComps/DetailParamInfo";
import DetailCommentInfo from "./childComps/DetailCommentInfo";
import DetailBottomBar from "./childComps/DetailBottomBar";

import Scroll from "../../components/common/scroll/Scroll";
import GoodsList from "../../components/content/goods/GoodsList";
import BackTop from "../../components/content/backTop/BackTop";
import Toast from "../../components/common/toast/Toast";

import {
  getDetail,
  Goods,
  Shop,
  GoodsParam,
  getRecommend,
} from "../../network/detail";
import { debounce } from "../../common/utils";

import { itemListenerMixin } from "../../common/mixin";
import { $bus } from "../../common/bus";

export default {
  name: "Detail",
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    Scroll,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    GoodsList,
    DetailBottomBar,
    BackTop,
    Toast,
  },
  // 混入
  mixins: [itemListenerMixin],
  data() {
    return {
      iid: null,
      topImages: [],
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [], // 记录滚动y轴坐标
      getThemeTopY: null, // 防抖函数
      currentIndex: 0,
      isShowBackTop: false,
      tabOffsetTop: 0,
      isShow: false,
      message: "",
      detail_nav: 0,
    };
  },
  methods: {
    imageLoad() {
      this.$refs.scroll.refresh();
      this.getThemeTopY();
    },
    titleClick(index) {
      console.log(index);
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 200);
    },
    wrapperScroll(position) {
      const positionY = -position.y;
      // console.log(position)
      let length = this.themeTopYs.length;
      for (let i = 0; i < length - 1; i++) {
        if (
          this.currentIndex !== i &&
          positionY >= this.themeTopYs[i] &&
          positionY < this.themeTopYs[i + 1]
        ) {
          this.currentIndex = i;
          console.log(this.currentIndex);
          this.$refs.nav.currentIndex = this.currentIndex;
        }
      }
      // 是否显示回到顶部
      // 1.判断BackTop按钮是否显示
      this.isShowBackTop = -position.y > 1000;
    },
    // 返回顶部按钮
    backClick() {
      this.$refs.scroll.scrollTo(0, 0);
    },
    addToCart() {
      // 1.获取购物车需要展示的信息
      const product = {};
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;
      // 2.将商品添加到购物车里
      // this.$store.commit('addCart', product)
      this.$store.dispatch("addCart", product).then((res) => {
        console.log(res);
        this.message = res;
        this.isShow = true;
        setTimeout(() => {
          this.isShow = false;
          this.message = "";
        }, 1500);
      });
    },
  },
  created() {
    // 1.保存传入的iid
    this.iid = this.$route.params.iid;
    // 2.根据iid请求详情数据
    getDetail(this.iid).then((res) => {
      // console.log(res);
      // 2.1获取顶部的图片轮播数据
      const data = res.result;
      this.topImages = data.itemInfo.topImages;
      // 2.2获取商品信息
      this.goods = new Goods(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );
      // 2.3创建店铺信息的对象
      this.shop = new Shop(data.shopInfo);
      // 2.4获取商品的详情信息
      this.detailInfo = data.detailInfo;
      // 2.5获取商品参数信息
      this.paramInfo = new GoodsParam(
        data.itemParams.info,
        data.itemParams.rule
      );
      // 2.6获取评论的信息
      if (data.rate.cRate !== 0) {
        this.commentInfo = data.rate.list[0];
      }
      // this.$nextTick(() => {
      // 根据最新的数据，对应的DOM是已经被渲染出来，值不对
      // 但是图片依然是没有加载完（目前获取到的offsetTop不包含其中的图片）
      //   this.themeTopYs = []
      //   this.themeTopYs.push(0);
      //   this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      //   this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      //   this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      //   console.log(this.themeTopYs);
      // });
    });
    // 3.请求推荐数据
    getRecommend().then((res) => {
      this.recommends = res.data.list;
    });
    // 4.给getThemeTopY赋值（对给this.themeTopYs赋值的操作进行防抖）
    this.$nextTick(() => {
      this.getThemeTopY = debounce(() => {
        this.themeTopYs = [];
        this.themeTopYs.push(0);
        this.themeTopYs.push(this.$refs.params.$el.offsetTop);
        this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
        this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
        // console.log(this.themeTopYs);
        this.themeTopYs.push(Number.MAX_VALUE);
      }, 200);
    });
  },
  unmounted() {
    console.log("destroyed");
    $bus.off("itemImageLoad", this.itemImgListener);
  },
};
</script>

<style>
#detail {
  position: relative;
  z-index: 9;
  background-color: #fff;
  height: 100vh;
}
.detail-bav {
  position: relative;
  z-index: 9;
  background-color: #fff;
}
.wrapper {
  height: calc(100% - 44px - 49px);
  /* overflow: hidden; */
}
</style>